package com.guestbook.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.entity.Admin;
import com.entity.Guestbook;
import com.guestbook.biz.AdminBiz;
import com.guestbook.biz.GuestbookBiz;
import com.utils.ValidatorUtils;
@Controller
@Scope(value="prototype")
public class GuestbookController
{
    @Autowired
    private GuestbookBiz guestbookBiz;
    @Autowired
    private AdminBiz adminBiz;
    
    @RequestMapping(value="/addGuestbook")
    public String add(Guestbook guestbook)
    {
        guestbookBiz.save(guestbook);
        return "redirect:/listGuestbook.action";
    }
    
    @RequestMapping(value="/listGuestbook")
    public String list(Map<String, Object> model)
    {
        List<Guestbook> guestbookList =guestbookBiz.findAllOrderById();
        model.put("guestbookList", guestbookList);
        return "Guestbooklist";
    }
    
    @RequestMapping(value="/login",method=RequestMethod.POST)
    public String login(@Valid Admin admin, BindingResult result,HttpSession session,Map<String, Object> model)
    {
        ValidatorUtils.valid(admin, model);
        Admin admin2 = adminBiz.checkPass(admin);
        if (admin2 != null)
        {
            session.setAttribute("admin", admin2);
            return "redirect:/secure/list.action";
        }
        return "login";
    }
    
    @RequestMapping(value="/login",method=RequestMethod.GET)
    public String prepareLogin(Admin admin ,Map<String, Object> model)
    {
        model.put("admin", admin);
        return "login";
    }
}
